import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import Layout from '@/layout/index.vue'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // get user info
          await store.dispatch('user/getInfo')
          // 添加动态路由
          const menus = store.getters.menuPermissions
          const dynamicRouters = buildDynamicRouters(menus)
          router.addRoutes(dynamicRouters)
          // 保存全局动态路由
          global.antRouter = dynamicRouters
          // 刷新界面，不再缓存旧页面，否则刷新页面会丢失路由记录，导致页面空白
          next({ ...to, replace: true })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

// 构建路由树
function buildDynamicRouters(menus) {
  if (!menus || menus.length === 0) {
    return []
  }
  return buildRouterTree(menus)
}

function buildRouterTree(menuTree) {
  const routerTree = []
  menuTree.forEach(tree => {
    const router = {}
    router.path = tree.routePath === '/' ? '/' : '/' + tree.routePath
    router.component = tree.componentPath === 'Layout' ? Layout : (resolve) => require([`@/views/${tree.componentPath}`], resolve)
    router.name = tree.routePath === '/' ? 'home' : tree.routePath
    const meta = {}
    meta.title = tree.menuName
    meta.icon = tree.icon
    router.meta = meta
    router.children = buildRouterChild(router, tree.children)
    routerTree.push(router)
  })
  return routerTree
}

function buildRouterChild(parent, children) {
  const routerChildren = []
  if (children) {
    children.forEach(child => {
      const routerChild = {}
      routerChild.path = child.routePath
      routerChild.component = child.componentPath === 'Layout' ? Layout : (resolve) => require([`@/views/${child.componentPath}`], resolve)
      router.name = child.routePath === '/' ? 'home' : child.routePath
      const meta = {}
      meta.title = child.menuName
      meta.icon = child.icon
      routerChild.meta = meta
      buildRouterChild(routerChild, child.children)
      routerChildren.push(routerChild)
    })
  }
  return routerChildren
}
